package com.twu.biblioteca;

import java.util.Scanner;

public class LoginAction implements Action {
    Library library;

    public LoginAction(Library library) {
        this.library = library;
    }

    public String execute() {
        String result;
        Scanner in = new Scanner(System.in);
        System.out.print("Please input the username: ");
        String username = in.nextLine();
        System.out.print("Please input the password: ");
        String password = in.nextLine();

        library.setCurrentUser(authenticate(username, password));
        if (!library.isUserLoggedIn()) {
            result = "Invalid username or password";
        } else {
            result = "Login successfully";
        }
        return result;
    }

    public User authenticate(String username, String password) {
        for (User user : library.getUsers()) {
            if (user.getLibraryNumber().equals(username) && user.checkPassword(password)){
                return user;
            }
        }
        return null;
    }


}
